<template>
  <!-- 包括用户列表，聊天主区域 -->
  <div class="im_container">
  
    <template>
      <Modal v-model="modal3" ok-text="捐赠完毕，知会一下作者" cancel-text="关 闭" title="捐赠t-io" @on-ok="ok3">
        <div>
          <img class='animated zoomInLeft' src="https://git.oschina.net/tywo45/t-io/raw/master/docs/pay/ali_300px-1.png" style="width: 240px;height: 240px">
          <img class='animated zoomInRight' src="https://git.oschina.net/tywo45/t-io/raw/master/docs/pay/wechat_300px-1.png" style="width: 240px;height: 240px">
        </div>
      </Modal>
    </template>
  
    <template>
      <Modal v-model="modal4" ok-text="确 定" cancel-text="关 闭" title="" width="600">
        <div>
  
          <Alert type="success" show-icon>
            友情提醒: 本站服务器配置极低，仅作演示，请勿DDos攻击----毕竟攻击这么一个小站，有损您的威名！
          </Alert>
  
          <img class='animated ' src="https://git.oschina.net/tywo45/t-io/raw/master/docs/centos/aliyun.png">
  
        </div>
      </Modal>
    </template>
    <!--<template>
                              <Modal v-model="tipmodal" title="" width="800">-->
    <div class="tipmodal animated" :class="{'zoomIn':showTipmodal,'zoomOut':!showTipmodal }" :style="{ display: showTipmodal ? '' : 'none'}">
      <div class="tipmodal_body">
        <p>本站前端技术栈
          <span class="t_content"> iview, webpack, vue, google-protobuf, core-js, animate.css, websocket, 高德地图 </span>
        </p>
        <p>本站后台技术栈
          <span class="t_content">
            <a href="https://git.oschina.net/tywo45/t-io" target="_blank">t-io</a>,
            <a href="https://git.oschina.net/tywo45/t-io/tree/master/src/zoo/http" target="_blank">tio-httpserver</a>,
            <a href="https://git.oschina.net/loolly/hutool" target="_blank">hutool</a>,
            <a href="https://github.com/google/protobuf" target="_blank">protobuf</a>,
            <a href="https://github.com/google/guava" target="_blank">guava</a>,
            <a href="https://git.oschina.net/tywo45/t-io" target="_blank">jdk1.7</a>
          </span>
        </p>
        <p>参考项目
          <span class="t_content">
            <a href="https://www.oschina.net/p/voovan" target="_blank">voovan</a>(cookie解析部分),
            <a href="https://git.oschina.net/generallycloud/baseio" target="_blank">baseio</a>(websocket编码解码部分)
          </span>
        </p>
        <p>选用t-io前，必须先了解一下它的正负面报道，自己理性判断各种言论，兼听则明
          <span class="t_content">
            <a href="https://my.oschina.net/yyxx9988/tweet/13485737" target="_blank">令人作呕的t-io（动弹）</a>
          </span>
          <span class="t_content">
            <a href="http://www.oschina.net/question/2617937_2243270" target="_blank">对t-io的质疑（讨论）</a>
          </span>
          <span class="t_content">
            <a href="https://my.oschina.net/u/2369298/blog/915435" target="_blank">30万长连接测试报告（博客）</a>
          </span>
          <span class="t_content">
            <a href="https://my.oschina.net/helyho/blog/919465" target="_blank">浅谈netty、t-io、Voovan（博客）</a>
          </span>
        </p>
        <p>除了t-io，你还有其它选择（只供参考，不担推荐责任）
          <span class="t_content">
            <a href="http://netty.io/" target="_blank">netty</a>、
            <a href="https://www.oschina.net/p/voovan" target="_blank">voovan</a>、
            <a href="https://git.oschina.net/generallycloud/baseio" target="_blank">baseio</a>
          </span>
  
        </p>
  
      </div>
      <div class="tipmodal_footer">
        <button type="button" class="ivu-btn ivu-btn-primary" @click="showTipmodal = false">
          <!---->
          <!---->
          <span>关 闭</span>
        </button>
  
      </div>
  
    </div>
    <!--</Modal>
                            </template>-->
  
    <!--视频区域-->
  
    <div id="tio_im_video_wrap" class="tio_im_video_wrap animated" :class="{'zoomIn':showVideo,'zoomOut':!showVideo }" :style="{ display: showVideo ? '' : 'none'}">
      <video id="tio_im_video" width="100%" height="100%" controls="" class="tio_im_video" poster="http://img.mingxing.com/upload/attach/2017/02-24/305975-2Rejru.jpg">
        <source src="http://lfsv.laifeng.com/872747401289404416.mp4" type="video/mp4">
        <!--<source src="https://www.helloweba.com/demo/html5video/movie.ogg" type="video/ogg">-->
        <!--你的浏览器不支持video标签。-->
        <embed src="http://blip.tv/play/gcMVgcmBAgA%2Em4v" type="application/x-shockwave-flash" width="100%" height="100%" allowscriptaccess="always" allowfullscreen="true">
      </video>
    </div>
  
    <!-- 聊天区域，包括聊天头部导航、聊天主区域、发送区域 start -->
    <div :class="{'im_chat_all_withoutvideo' : !showVideo, 'im_chat_all' : showVideo}">
  
      <!-- 聊天头部导航 start -->
      <div class="im_group_info">
        <!--<a href="http://img.mingxing.com/upload/attach/2017/02-24/305975-i9Qcmu.jpg" target="_blank">
                                                                                                              <img class="animated zoomInRight im_group_avatar" src="http://img.mingxing.com/upload/attach/2017/02-24/305975-i9Qcmu.jpg">
                                                                                                            </a>
                                                                                                            <div>
                                                                                                              <div class='animated bounceIn im_group_name'>杨幂粉丝群</div>
                                                                                                              <div class="animated bounceIn im_online_count">{{clients.length}} / {{recordCount}}</div>
                                                                                                            </div>-->
        <div class="ivu-tabs-nav-container">
          <div class="ivu-tabs-nav-wrap">
            <div class="ivu-tabs-nav-scroll">
              <div class="ivu-tabs-nav">
                <div class="ivu-tabs-ink-bar ivu-tabs-ink-bar-animated" style="display: block; width: 105px; transform: translate3d(0px, 0px, 0px);"></div>
                <div class="ivu-tabs-tab ivu-tabs-tab-active">
                  <Badge :count="notReadCount" overflow-count="9999">
                    <i class="ivu-icon ivu-icon-chatbubble-working"></i> 聊 天
                  </Badge>
  
                  <!---->
                </div>
                <div class="ivu-tabs-tab">
                  <i class="ivu-icon ivu-icon-person-stalker"></i> 游 戏
                  <!---->
  
                </div>
                <div class="ivu-tabs-tab">
                  <i class="ivu-icon ivu-icon-mic-a"></i> 直 播
                  <!---->
                </div>
                <div class="ivu-tabs-tab">
                  <i class="ivu-icon ivu-icon-social-tux"></i> 3D 图
                  <!---->
                </div>
              </div>
              <!---->
            </div>
          </div>
        </div>
      </div>
      <!-- 聊天头部导航 end -->
  
      <div title="下面有开关可以开启和关闭3D显示" :style="{ display: showD3 ? '' : 'none'}" class="d3_outside_container" id="d3">
        <div class="d3_rect-wrap">
          <div class="d3_container">
            <div id="d3_top" @click="d3clicked('showD3top')" :class="{'d3_top d3_slide': showD3top}"></div>
            <div id="d3_bottom" @click="d3clicked('showD3bottom')" :class="{'d3_bottom d3_slide': showD3bottom}"></div>
            <div id="d3_left" @click="d3clicked('showD3left')" :class="{'d3_left d3_slide': showD3left}"></div>
            <div id="d3_right" @click="d3clicked('showD3right')" :class="{'d3_right d3_slide': showD3right}"></div>
            <div id="d3_front" @click="d3clicked('showD3front')" :class="{'d3_front d3_slide': showD3front}"></div>
            <div id="d3_back" @click="d3clicked('showD3back')" :class="{'d3_back  d3_slide': showD3back }"></div>
          </div>
        </div>
      </div>
  
      <div class="im_chat_content_wrap">
  
        <div class="im_map_wrap animated" :class="{'zoomIn':showMap,'zoomOut':!showMap }" id="im_map_wrap" :style="{ display: showMap ? '' : 'none'}">
          待完善
        </div>
  
        <div class="im_chat_content" id="chat_main" @scroll="chatScrolled">
          <ul>
            <transition-group name="custom-classes-transition" enter-active-class="animated bounceIn" leave-active-class="animated fadeOutRight" tag="span">
              <template v-for="(chatRespBody, index) in chatRespBodys">
  
                <!--普通聊天-->
                <template v-if="chatRespBody.c ==  'COMMAND_CHAT_RESP'">
                  <!--自己发的消息-->
                  <li v-if="chatRespBody.fromclient.user.id == currUserid" class="bounceInRight im_chat_content_mine" :key="chatRespBody">
                    <div class="im_chat_userinfo">
                      <img v-bind:src="chatRespBody.fromclient.user.avatar">
                      <cite>
                        <i>{{ chatRespBody.date + ' ' + formatRegion(chatRespBody.fromclient.region) }}</i>{{ chatRespBody.fromclient.user.nick }}</cite>
                    </div>
                    <!--<template v-else>-->
                    <div class="im_chat_text_mine" v-html="chatRespBody.text">
                    </div>
                    <!--</template>-->
                  </li>
  
                  <!--别人发的消息-->
                  <li v-if="chatRespBody.fromclient.user.id != currUserid" class="bounceInLeft" :key="chatRespBody">
                    <div class="im_chat_userinfo">
                      <img v-bind:src="chatRespBody.fromclient.user.avatar">
                      <cite>{{ chatRespBody.fromclient.user.nick }}
                        <i>{{ formatRegion(chatRespBody.fromclient.region) + ' ' + chatRespBody.date }}</i>
                      </cite>
                    </div>
  
                    <!--<template v-if="chatRespBody.text ==  'c:get-im-code'">
                                                                                                                                                                                                                <div class="im_chat_text">
                                                                                                                                                                                                                  <Button type='primary' @click='modal1 = true'>点击下载本站源代码</Button>
                                                                                                                                                                                                                </div>
                                                                                                                                                                                                              </template>-->
                    <!--<template v-else>-->
                    <div class="im_chat_text" v-html="chatRespBody.text">
                    </div>
                    <!--</template>-->
                  </li>
  
                </template>
  
                <!--进群组通知-->
                <template v-if="chatRespBody.c ==  'COMMAND_JOIN_GROUP_NOTIFY_RESP'">
                  <li class="im_system_notice bounceIn" :key="chatRespBody" enter-active-class="animated bounceIn" leave-active-class="animated bounceOut">
                    <span>{{chatRespBody.client.user.nick}}加入群聊 【{{chatRespBody.client.region}}】【{{chatRespBody.client.useragent}}】</span>
                  </li>
                </template>
  
                <!--离开群组通知-->
                <template v-if="chatRespBody.c == 'COMMAND_EXIT_GROUP_NOTIFY_RESP'">
                  <li class="im_system_notice" :key="chatRespBody">
                    <span>{{chatRespBody.client.user.nick}}离开了群聊 【{{chatRespBody.client.region}}】【{{chatRespBody.client.useragent}}】</span>
                  </li>
                </template>
  
              </template>
  
            </transition-group>
          </ul>
        </div>
        <!--<i @click="roll_hintClicked" :title="needRoll ? '目前是自动滚屏模式' : '没有开启滚屏模式'" id="roll_hint" :class="{'iconoo-caretDownCircle': !needRoll, 'iconoo-caretUpCircle': needRoll, 'roll_hint':true }"></i>-->
  
        <div class="fun_area">
          <!--<i class="ivu-icon ivu-icon-chevron-up"></i>-->
          <!--{{needRoll ? '目前是自动滚屏模式，点击切换' : '目前是手动滚屏模式，点击切换'}}-->
  
          <div @click="showTipmodal = !showTipmodal">
            <i-switch size="large" :value="showTipmodal">
              <span slot="open">提示</span>
              <span slot="close">提示</span>
              </span>
            </i-switch>
          </div>
  
          <div @click="toggleMap()">
            <i-switch size="large" :value="showMap">
              <span slot="open">地图</span>
              <span slot="close">地图</span>
              </span>
            </i-switch>
          </div>
  
          <div @click="toggleD3">
            <i-switch size="large" :value="showD3">
              <span slot="open">3D</span>
              <span slot="close">3D</span>
            </i-switch>
          </div>
  
          <div @click="toggleVideo">
            <i-switch size="large" :value="showVideo">
              <span slot="open">视频</span>
              <span slot="close">视频</span>
            </i-switch>
          </div>
  
          <div @click="roll_hintClicked">
            <i-switch size="large" :value="needRoll">
              <span slot="open">滚屏</span>
              <span slot="close">滚屏</span>
            </i-switch>
          </div>
  
        </div>
  
      </div>
  
      <div class="im_send_div">
        <span class="im_send_textarea_span">
          <textarea class="im_send_textarea" placeholder="输入内容后，按回车即可发送，输入s:xxx会显示百度搜索xxx的结果'" v-on:keyup.enter='sendBtnClicked' name='' id='text'></textarea>
        </span>
  
        <span class="im_send_btn_span">
          <button v-on:click='sendBtnClicked' type="button" class="ivu-btn ivu-btn-primary ">发 送</button>
          <button type="button" v-on:click="sendBtnClicked('x','c:idiom')" class="ivu-btn ivu-btn-success">
            <span>成 语</span>
          </button>
          <button type="button" v-on:click="sendBtnClicked('x','c:stat')" class="ivu-btn ivu-btn-success">
            <span>统 计</span>
          </button>
          <!-- <button type="button" v-on:click="sendBtnClicked('x','c:mm-10')" class="ivu-btn ivu-btn-success">
                    <span>美 图</span>
                  </button> -->
          <button type="button" class="ivu-btn ivu-btn-success" @click="modal4=true;">
            <span>服务器</span>
          </button>
          <button type="button" class="ivu-btn ivu-btn-success" @click="modal3=true;">
            <span>捐 助</span>
          </button>
  
        </span>
      </div>
  
    </div>
    <!-- 聊天区域，包括聊天头部导航、聊天主区域、发送区域 end -->
  
    <!-- 用户列表 -->
    <div class="im_userlist_wrap">
      <span :title="'在线人数' + recordCount + ',当前页显示' + clients.length" class="im_online_count" id="im_online_count">{{clients.length}} / {{recordCount}}</span>
      <div class="im_userlist">
        <ol class="im_userlist_ol">
          <transition-group name="userlist-transition" enter-active-class="animated zoomInRight" leave-active-class="animated zoomOutLeft" tag="div">
            <li :key="client" v-for="(client,index) in clients" :title="formatRegion(client.region) + ' | ' + client.useragent">
  
              <span class="im_userlist_avatar_wrap">
                <img class="im_userlist_avatar" v-bind:src="client.user.avatar" onerror="this.src='http://img.mingxing.com/upload/attach/2017/02-24/305975-i9Qcmu.jpg'">
              </span>
  
              <span class="im_userlist_nickandother">
                <span class="nick">{{ client.user.nick }}</span>
                <!--<span style="font-size:10px;color:#aaa">{{formatRegion(client.region) + ' | ' + client.useragent}}</span>-->
  
                <span class="nick_attached" style="display:block;">{{formatRegion(client.region)}}
                  <a v-bind:href="'https://www.baidu.com/s?word=' + client.ip" target="_blank">{{client.ip}}</a>
                </span>
  
                <span class="nick_attached">{{client.useragent}}</span>
              </span>
            </li>
          </transition-group>
        </ol>
      </div>
    </div>
  
  </div>
</template>

<script>

// var Vue = require("vue");

var Protobuf = require("google-protobuf");

// import * as Clipboard from 'clipboard';
// var Bytebuffer = require("bytebuffer");
import ArrayUtil from './util/ArrayUtil.js';
import Tio from './util/Tio.js';
import D3 from './util/D3.js';

import ImProto from './chat_pb.js';

import ImHandler from './ImHandler.js';
import ImListener from './ImListener.js';
import WsClient from './WsClient.js';

export default {
  name: 'im',
  components: {
    //chat, userlist
  },
  data() {
    return {
      clients: [

      ],
      chatRespBodys: [

      ],
      recordCount: 0,
      currUser: null,
      currUserid: null,
      // modal1: false,
      // modal2: false,
      modal3: false,
      modal4: false,
      needRoll: true,
      showVideo: false,
      notReadCount: 1,

      tipmodal: true,

      showD3top: true,
      showD3bottom: true,
      showD3left: true,
      showD3right: true,
      showD3front: true,
      showD3back: true,
      showD3: false,

      showMap: false,
      showTipmodal: false
    }

  },
  methods: {
    d3clicked: function (key) {
      console.log(key, this[key]);
      // this[key] = false;//!this[key];
    },
    ok3() {
      window.open("mailto:tywo45@163.com");
    },

    toggleD3: function () {
      // con
      this.showD3 = !this.showD3;

      if (this.showD3) {
        let index = (this.d3_background_index++) % this.d3_background_count;
        let data = this.d3_background_data[index];


        let top = document.getElementById("d3_top");
        let bottom = document.getElementById("d3_bottom");
        let left = document.getElementById("d3_left");
        let right = document.getElementById("d3_right");
        let front = document.getElementById("d3_front");
        let back = document.getElementById("d3_back");

        top.style.background = "url(" + data.top + ") no-repeat";
        bottom.style.background = "url(" + data.bottom + ") no-repeat";
        left.style.background = "url(" + data.left + ") no-repeat";
        right.style.background = "url(" + data.right + ") no-repeat";
        front.style.background = "url(" + data.front + ") no-repeat";
        back.style.background = "url(" + data.back + ") no-repeat";


        top.style.backgroundSize = "100% 100%";
        bottom.style.backgroundSize = "100% 100%";
        left.style.backgroundSize = "100% 100%";
        right.style.backgroundSize = "100% 100%";
        front.style.backgroundSize = "100% 100%";
        back.style.backgroundSize = "100% 100%";
      }

      document.getElementById("d3").style.display = this.showD3 ? "" : "none";
    },
    toggleVideo: function () {
      this.showVideo = !this.showVideo;

      var tio_im_video = document.getElementById("tio_im_video");
      try {
        if (this.showVideo) {
          // tio_im_video.play();
        } else {
          tio_im_video.pause();
        }
      } catch (e) {
        console.error(e);
      }
    },

    //参数为null时为切换状态，不为null时为赋值操作
    toggleMap: function (showMap) {
      if (arguments.length == 1) {
        this.showMap = showMap;
      } else {
        this.showMap = !this.showMap;
      }


      if (this.showMap) {
        let mapObj = new AMap.Map('im_map_wrap', {
          resizeEnable: true,
          // zoom: 10,
          // center: [118.4253323, 31.80452471]
        });

        let clients = this.clients;
        if (!clients) {
          return;
        }

        for (let index = 0; index < clients.length; index++) {
          let c = clients[index];
          console.log(c);

          if (!c.geolocation) {
            continue;
          }

          // mapObj.setBounds(citybounds); //把地图显示当前城市
          let MarkerListener = function (_marker, avatar, nick) {
            this.click = function (e) {
              // _marker.setContent("<div class='im_map_marker_wrap'><img class='im_map_marker_img' src='" + avatar + "'><div class='im_map_marker'>" + nick + "</div></div>");
            };
            this.mouseout = function (e) {
              // _marker.setContent("");
            };
          };

          let marker = new AMap.Marker({
            position: [c.geolocation.lng, c.geolocation.lat],//marker所在的位置
            // content:"<div class='im_map_marker_wrap'><img class='im_map_marker_img' src='"+c.user.avatar+"'><div class='im_map_marker'>"+c.user.nick+"</div></div>",
            // icon:"http://orkhgo5qu.bkt.clouddn.com/tx/31.jpg",
            title: c.user.nick + "[" + c.address.formattedaddress + "]",
            map: mapObj//创建时直接赋予map属性
          });
          //也可以在创建完成后通过setMap方法执行地图对象
          marker.setMap(mapObj);
          let markerListener = new MarkerListener(marker, c.user.avatar, c.user.nick);
          AMap.event.addListener(marker, 'click', markerListener.click);
        }




      }




    },

    chatScrolled: function () {
      try {
        let div = document.getElementById('chat_main');
        //38758 286 286 39044 39044
        // console.log(div.scrollTop, div.clientHeight, div.offsetHeight, div.scrollHeight, div.scrollHeight);
        if ((div.scrollTop + div.clientHeight + 10) >= div.scrollHeight || (div.scrollTop + div.offsetHeight + 10) >= div.scrollHeight) {  //38524 38810;  //26923 38810
          this.notReadCount = 0;
        }
      } catch (e) {
        console.error(e);
      }

    },

    sendBtnClicked: function () {
      // console.log(arguments);
      // console.log(this);
      // var clipboard = new Clipboard('.btn');
      // console.log(clipboard);


      var textele = document.getElementById('text');
      if (arguments.length == 2) {
        textele.value = arguments[1];
      }

      // if ('c:get-im-code' == textele.value) {
      //   this.modal1 = true;//显示下载源代码的框
      // }


      //发消息
      let chatReqBody = new ImProto.ChatReqBody();
      textele.value = textele.value.replace('\r', '');
      textele.value = textele.value.replace('\n', '');
      chatReqBody.setText(textele.value);
      chatReqBody.setGroup("g");
      chatReqBody.setType(ImProto.ChatType.CHAT_TYPE_PUBLIC);

      Tio.send(ImProto.Command.COMMAND_CHAT_REQ, chatReqBody, this.ws);

      // if (textele.value.indexOf("c:") >= 0 || (textele.value == '五方会谈') || (textele.value == '来电话了')) {

      // } else {
      textele.value = "";
      // }

    }, formatRegion(region) {
      var arr = region.split("|");
      var validArr = [];
      for (var i = 0; i < arr.length; i++) {
        var e = arr[i];
        if (e && e != '0') {
          validArr.push(e);
        }
      }
      if (validArr.length == 0) {
        return "";
      } else if (validArr.length == 1) {
        return validArr[0];
      } else {
        return validArr[validArr.length - 2] + validArr[validArr.length - 1];
      }
    }, roll_hintClicked() {
      this.needRoll = !this.needRoll;

      if (this.needRoll) {
        let div = document.getElementById('chat_main');
        div.scrollTop = div.scrollHeight;
        this.notReadCount = 0;
      }
    }
  },
  mounted() {
    // let wsServer = "127.0.0.1";  //本机
    // let wsServer = "t-io.org";  //莉
    let wsServer = "t-io.org";  //谭
    let wsPort = 9321;
    let url = "ws://" + wsServer + ":" + wsPort + "?xx=tan&yy=" + encodeURIComponent("?#@!$%^&=d");
    // console.log(url);
    let imHandler = new ImHandler(this, this.$refs.userlist, this.$refs.chat);
    let imListener = new ImListener(this, imHandler);
    let heartbeatTimeout = 90 * 1000;
    let reconnInterval = 1000;
    //constructor(url, listener, heartbeatTimeout, reconnInterval)
    let wsClient = new WsClient(this, url, imHandler, imListener, heartbeatTimeout, reconnInterval);
    let ws = wsClient.connect();

    this.ws = ws;
    this.imHandler = imHandler;
    this.imListener = imListener;
    this.wsClient = wsClient;
    this.wsServer = wsServer;
    this.wsPort = wsPort;

    this.d3_background_index = 0;
    this.d3_background_data = D3.data();
    this.d3_background_count = this.d3_background_data.length;
    // console.log(this.d3_background_count);

    this.$watch('imHandler.im.chatRespBodys', function (curVal, oldValue) {
      console.log(this);
      if (!this.needRoll) {
        this.notReadCount++;
        return;
      }

      this.notReadCount = 0;
      setTimeout(function () {
        let div = document.getElementById('chat_main');
        div.scrollTop = div.scrollHeight;

      }, 10);
    }, {
        deep: true
      });

    // try {
    //   this.imdb = openDatabase('imdb', '1.0', 'im db', 2 * 1024 * 1024);
    //   console.log(this.imdb);

    //   this.imdb.transaction(function (tx) {
    //     tx.executeSql('CREATE TABLE IF NOT EXISTS chatItems (id unique, userid, date, item)');
    //   });
    // } catch (error) {

    // }
  }
}



</script>

<style scoped>
#im {
  height: calc(100%);
}
</style>

